package com.hmy.security.util;

import lombok.Data;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class CacheUtil {

    @Data
    private static class CacheNode{
        private String v;
        private List<String> vList;
        private Long expireTime;

        public boolean expired(){
            if (expireTime == -1) {
                return false;
            }
            return System.currentTimeMillis() >= expireTime;
        }
    }

    private final Map<String, CacheNode> cacheMap = new ConcurrentHashMap<>();

    public void del(String key) {
        cacheMap.remove(key);
    }

    public void set(String key, String value){
        set(key, value, -1L);
    }

    public void set(String key, String value, Long expireTime){
        CacheNode cacheNode = cacheMap.get(key);
        if (cacheNode == null) {
            cacheNode = new CacheNode();
        }
        cacheNode.setV(value);
        cacheNode.setExpireTime(expireTime);
        cacheMap.put(key, cacheNode);

    }

    public String get(String key) {
        CacheNode cacheNode = cacheMap.get(key);
        if (cacheNode == null){
            return null;
        }
        if (cacheNode.expired()) {
            cacheMap.remove(key);
            return null;
        }
        return cacheNode.getV();
    }

    public void lSet(String key, String value) {
        lSet(key, value, -1L);
    }

    public void lSet(String key, String value, Long expireTime) {
        lSet(key, Collections.singletonList(value), expireTime);
    }

    public void lSet(String key, List<String> values) {
        lSet(key, values, -1L);
    }

    public void lSet(String key, List<String> values, Long expireTime) {
        CacheNode cacheNode = cacheMap.get(key);
        if (cacheNode == null) {
            cacheNode = new CacheNode();
            cacheNode.setVList(new ArrayList<>());
        }
        cacheNode.getVList().addAll(values);
        cacheNode.setExpireTime(expireTime);
        cacheMap.put(key, cacheNode);
    }

    public List<String> lGet(String key) {
        CacheNode cacheNode = cacheMap.get(key);
        if (cacheNode == null){
            return null;
        }
        if (cacheNode.expired()) {
            cacheMap.remove(key);
            return null;
        }
        return cacheNode.getVList();
    }

    public void lRm(String key, String value) {
        CacheNode cacheNode = cacheMap.get(key);
        if (cacheNode != null){
            if (cacheNode.expired()) {
                cacheMap.remove(key);
            } else {
                cacheNode.getVList().remove(value);
                if (cacheNode.getVList().size() == 0) {
                    cacheMap.remove(key);
                }
            }
        }
    }


}
